<template>
  <div style="width: 100%; background-color: white">
    <el-card style="width: 80%; margin: 0 auto; border: unset" shadow="never">
      <div slot="header">
        <span style="text-align: center">{{
          $t('email.createMarketingTask')
        }}</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <el-form ref="form" :rules="formRules" :model="form" label-width="150px">
        <el-form-item :label="$t('email.taskName')" prop="Title">
          <el-input
            v-model="form.Title"
            maxlength="40"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('email.senderName')" prop="emailSenderName">
          <el-autocomplete
            v-model="form.emailSenderName"
            :fetch-suggestions="querySearchAsync"
            maxlength="20"
            show-word-limit
            class="w-full"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item :label="$t('email.receiveReply')" prop="ReplyEmail">
          <div style="display: flex">
            <el-input
              v-model="form.ReplyEmail"
              maxlength="50"
              show-word-limit
            ></el-input>
            <el-checkbox
              style="width: 10%; min-width: 180px; margin-left: 1%"
              v-model="form.ShowAsEmail"
              >{{ $t('email.showAsSenderEmail') }}</el-checkbox
            >
          </div>
        </el-form-item>
        <el-form-item :label="$t('common.receiver')">
          <template>
            <el-radio-group v-model="AddresseeType" @change="AddresseeChange">
              <!-- <el-radio label="1" border disabled>选择客户分组</el-radio> -->
              <!-- <el-radio label="2" border disabled>搜索客户</el-radio> -->
              <el-radio label="3" border>{{
                $t('email.importEmail')
              }}</el-radio>
              <el-radio label="4" border>{{ $t('email.copyPaste') }}</el-radio>
            </el-radio-group>
            <template>
              <div v-if="this.AddresseeType === '1'">
                <el-card shadow="never" style="margin-top: 25px">
                  {{ $t('email.selectCustomerGroup') }}
                </el-card>
              </div>
              <div v-if="this.AddresseeType === '2'">
                <el-card shadow="never" style="margin-top: 25px">
                  {{ $t('email.searchCustomer') }}
                </el-card>
              </div>
              <div v-if="this.AddresseeType === '3'">
                <el-card shadow="never" style="margin-top: 25px">
                  <div style="height: 220px">
                    <div style="margin-right: 20px">
                      <el-tag type="warning">{{
                        $t('email.enterEmailsLineByLine')
                      }}</el-tag>
                      <el-button
                        size="mini"
                        type="success"
                        style="
                          margin-left: 5px;
                          display: inline-block;
                          float: right;
                        "
                        @click="handleImportEmails"
                        >{{ $t('email.startImport') }}</el-button
                      >
                      <el-button
                        size="mini"
                        slot="trigger"
                        type="primary"
                        style="display: inline-block; float: right"
                        @click="handleShowUploadEmails"
                        >{{ $t('email.importEmail') }}</el-button
                      >
                    </div>
                    <div style="margin-top: 10px">
                      <div
                        style="height: 10%; margin: 10px; width: 40%"
                        v-show="this.showUploadEmailsVisible"
                      >
                        <el-upload
                          ref="uploadEmail"
                          :multiple="false"
                          action=""
                          accept=".txt"
                          :on-change="changeFile"
                          :http-request="uploadHandler"
                          :auto-upload="false"
                          style=""
                        >
                          <el-button
                            class="mr-2"
                            plain
                            slot="trigger"
                            type="primary"
                            size="mini"
                            ><i class="el-icon-upload mr-1 font-size-14"></i>
                            {{ $t('email.readFile') }}</el-button
                          ><span style="margin-left: 10px">{{
                            $t('email.supportTxtMax2M')
                          }}</span>
                        </el-upload>
                      </div>
                      <el-col :span="24">
                        <el-input
                          type="textarea"
                          :autosize="{ minRows: 8, maxRows: 9 }"
                          :placeholder="$t('email.typeEmailLineByLine')"
                          v-model="importEmailTemp"
                          id="readTxt"
                          accept=".txt"
                        >
                        </el-input>
                      </el-col>
                    </div>
                  </div>
                </el-card>
              </div>
              <div v-if="this.AddresseeType === '4'">
                <el-card shadow="never" style="margin-top: 25px">
                  <form action="">
                    <el-input
                      :placeholder="$t('common.enter', [$t('email.content')])"
                      v-model="addresseeTemp"
                      style="align: center"
                      clearable
                      class="input-with-select"
                      prop="Addressee"
                    >
                      <el-button
                        slot="append"
                        icon="el-icon-plus"
                        @click="addNewAddressee"
                        >{{ $t('email.addRecipient') }}</el-button
                      >
                    </el-input>
                  </form>
                  <div class="receiving">
                    <el-table :data="paginatedEmails" max-height="550">
                      <el-table-column
                        :label="$t('common.name')"
                        align="center"
                      >
                        <template slot-scope="scope">
                          {{ scope.row.name }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        :label="$t('email.recipient')"
                        align="center"
                      >
                        <template slot-scope="scope">
                          {{ scope.row.email }}
                        </template>
                      </el-table-column>
                      <el-table-column align="center">
                        <template slot="header">
                          <el-input
                            v-model="searchAddressee"
                            size="mini"
                            :placeholder="$t('email.enterSearchAddressee')"
                          />
                        </template>
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            plain
                            @click="handleEmailRemove(scope.row)"
                            >{{ $t('email.remove') }}</el-button
                          >
                        </template>
                      </el-table-column>
                    </el-table>
                    <pagination
                      v-show="total > 0"
                      :total="total"
                      :page.sync="page"
                      :limit.sync="limit"
                    />
                  </div>
                </el-card>
              </div>

              <!-- <el-alert
                type="info"
                :closable="false"
                description="√ 已选 0 今日可用 1500 可用额度 2855">
              </el-alert> -->
            </template>
          </template>
        </el-form-item>
        <el-divider></el-divider>
        <!-- <span>
        <el-switch
          v-model="form.useActionHelperModule"
          active-color="#13ce66"
          inactive-color="#ff4949"
          style="margin:0px 20px 30px 110px;float:left;"
          >
        </el-switch><span style="float:left;">启用【行动助手】写信引导模式</span>
        </span> -->
        <div style="clear: both"></div>
        <el-form-item :label="$t('email.subject')" prop="EmailSubject">
          <el-input v-model="form.EmailSubject" show-word-limit></el-input>
        </el-form-item>
        <!-- <el-form-item label="附件:"> -->
        <!-- <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="handleChange"
            :file-list="fileList">
            <span style="color:orange;"><i class="el-icon-link"/>点击上传</span>

            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload> -->
        <!-- </el-form-item> -->
        <el-form-item :label="$t('email.content')">
          <el-row>
            <!-- <el-button type="success" size="mini" disabled plain>插入昵称</el-button>
            <el-button type="success" size="mini" disabled plain>插入图片</el-button>
            <el-button type="success" size="mini" disabled plain>新建模板</el-button> -->
            <el-button
              type="success"
              size="mini"
              plain
              @click="handleSelectTemplate"
              >{{ $t('email.chooseTemplate') }}</el-button
            >
            <!-- <el-button type="success" size="mini" disabled plain>选择活动页</el-button>
            <el-button type="success" size="mini" disabled plain>导入模板</el-button>
            <el-button type="success" size="mini" disabled plain>切换源码</el-button>
            <el-button type="success" size="mini" disabled plain>预览</el-button> -->
          </el-row>
          <tinymce-page
            value=" "
            v-model="form.EmailContent"
            :menubar="menubar"
            prop="EmailContent"
            :height="500"
          ></tinymce-page>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item :label="$t('email.TimingSend')">
          <el-date-picker
            v-model="form.TimingTransmission"
            type="datetime"
            :placeholder="$t('customer.selectDate')"
          >
          </el-date-picker>
        </el-form-item>
        <div class="footer-operate">
          <el-button
            size="small"
            type="primary"
            @click="submitForm('form', 1)"
            >{{ $t('common.save') }}</el-button
          >
          <el-button
            size="small"
            type="success"
            @click="submitForm('form', 2)"
            >{{ $t('email.saveAndSend') }}</el-button
          >
          <!-- <el-button size="small" type="warning" @click="cancleForm()">取 消</el-button> -->
        </div>
      </el-form>
    </el-card>
    <select-template
      :show.sync="showSelectTemplateVisible"
      @updateTemplate="handleTemplateChange"
    />
  </div>
</template>
<script>
import TinymcePage from '../Tinymce/index.vue'
import { postAction, postLongTimeAction, getAction } from '@/api/common'
import SelectTemplate from '../emailTemplate/selectTemplate.vue'
import Pagination from '@/components/Pagination/index'
import { validateEmail } from '@/utils/validate'

export default {
  name: 'baseform',
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    emailsTemp: {
      type: Array,
      default: () => [],
    },
    source: {
      type: [String, Number],
      default: '',
    },
  },
  components: {
    TinymcePage,
    SelectTemplate,
    Pagination,
  },
  data: function () {
    return {
      fileList: [
        {
          name: 'food.jpeg',
          url:
            'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
        {
          name: 'food2.jpeg',
          url:
            'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
      ],
      form: {
        Title: '',
        emailSenderName: '',
        ShowAsEmail: false,
        ReplyEmail: '',
        Addressee: [],
        EmailSubject: '',
        TimingTransmission: null,
        EmailContent: '',
        AddresseeEmailArray: [],
        TypeOfRequest: 'Server',
        State: 1,
      },
      AddresseeTemp: null,
      addresseeTemp: null,
      importEmailTemp: null,
      // importEmailTempArray: [],
      AddresseeType: '4',
      showSelectTemplateVisible: false,
      showUploadEmailsVisible: false,
      searchAddressee: '',
      formRules: {
        Title: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.taskName')]),
            trigger: 'blur',
          },
        ],
        emailSenderName: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.sender')]),
            trigger: 'blur',
          },
        ],
        ReplyEmail: [
          {
            required: true,
            message: this.$t('common.enter', [
              this.$t('email.replyEmailAddress'),
            ]),
            trigger: 'blur',
          },
          { trigger: 'blur', validator: validateEmail },
        ],
        Addressee: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('common.receiver')]),
            trigger: 'change',
          },
        ],
        EmailSubject: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.emailSubject')]),
            trigger: 'blur',
          },
          // { min: 3, max: 50, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        EmailContent: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('email.emailContent')]),
            trigger: 'blur',
          },
          // { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' }
        ],
      },
      fromPage: null,
      menubar: 'edit view',
      page: 1,
      limit: 20,
    }
  },
  watch: {
    show(val) {
      this.$emit('update:show', val)
    },
    emailsTemp(val) {
      this.form.Addressee = val ?? []
      this.form.AddresseeEmailArray = this.form.Addressee.map((m) => m.email)
    },
  },
  created() {
    this.form = {
      Title: '',
      emailSenderName: '',
      ShowAsEmail: false,
      ReplyEmail: '',
      Addressee: [],
      EmailSubject: '',
      TimingTransmission: null,
      EmailContent: '',
      AddresseeEmailArray: [],
      TypeOfRequest: 'Server',
      State: 1,
    }
    this.fromPage = this.$route.query.fromPage
    // const emailsTemp = [{ id: 1, name: '大胖纸', email: '123456@163.com' }, { id: 2, name: '二撒子', email: '123123@126.com' }]
    const emailsTemp = this.emailsTemp ?? []
    this.form.Addressee = emailsTemp
    this.form.AddresseeEmailArray = this.form.Addressee.map((m) => m.email)
  },
  computed: {
    filteredEmails() {
      return this.form.Addressee.filter(
        (data) =>
          !this.searchAddressee ||
          data.email.toLowerCase().includes(this.searchAddressee.toLowerCase())
      )
    },
    paginatedEmails() {
      const start = (this.page - 1) * this.limit
      const end = start + this.limit
      return this.filteredEmails.slice(start, end)
    },
    total() {
      return this.filteredEmails?.length || 0
    },
    server() {
      return this.$route.query.server
    },
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    submitForm(formName, state) {
      this.form.State = state
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 增加对漏网之鱼的验证
          // 检测收件列表
          if (this.form.AddresseeEmailArray.length === 0) {
            this.$message({
              message: this.$t('email.pleaseAddRecipient'),
              type: 'warning',
            })
            return false
          }
          // 检测编辑邮件
          if (this.form.EmailContent.length === 0) {
            this.$message({
              message: this.$t('email.pleaseEditEmailContent'),
              type: 'warning',
            })
            return false
          }
          this.form.server = this.server
          postLongTimeAction(this.form, 'EmailMarketing/Create').then((res) => {
            console.log(res)
            if (res.code === 20000) {
              this.$message({
                message: this.$t('email.createMarketingTaskSuccessfully'),
                type: 'success',
              })
              if (this.source === 1) {
                this.$emit('closeAction')
              } else {
                this.$router.push('/email/emailMarketingTask/' + this.fromPage)
              }
            } else {
              this.$message({
                message: this.$t('email.createMarketingTaskFailed'),
                type: 'warning',
              })
            }
            this.$emit('update:show', false)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
      // const res = await
      // this.$message.success('提交成功')
      // this.$emit('update:show', false)
      // this.$emit('closeAction')
    },
    AddresseeChange(val) {
      // this.AddresseeType = val
      console.log('切换了', val)
    },
    addNewAddressee() {
      const addresseeTemp = this.addresseeTemp ? this.addresseeTemp.trim() : ''
      // 验证是否为空
      if (addresseeTemp.length !== 0) {
        // 验证是否邮箱格式
        if (this.checkEmailAddress(addresseeTemp)) {
          // 验证是否重复
          if (this.form.AddresseeEmailArray.indexOf(addresseeTemp) > -1) {
            this.$message({
              message: this.$t('email.emailExists'),
              type: 'warning',
            })
            return false
          } else {
            this.handleGetIdByEmail(addresseeTemp)
          }
        } else {
          this.$message({
            message: this.$t('email.emailIncorrect'),
            type: 'warning',
          })
          return false
        }
      } else {
        this.$message({
          message: this.$t('email.cannotBeEmpty'),
          type: 'warning',
        })
        return false
      }
    },
    handleGetIdByEmailRet(addresseeTemp) {
      // TODO: 实现批量操作
      postAction({ email: addresseeTemp }, 'Customer/GetIdByEmail').then(
        (res) => {
          if (res.data) {
            return res.data
          } else {
            return {
              email: addresseeTemp,
              name: this.$t('common.empty'),
              id: null,
            }
          }
        }
      )
    },
    handleGetIdByEmail(addresseeTemp) {
      // TODO: 实现批量操作
      postAction({ email: addresseeTemp }, 'Customer/GetIdByEmail').then(
        (res) => {
          if (res.data) {
            this.form.Addressee.push(res.data)
          } else {
            this.form.Addressee.push({
              email: addresseeTemp,
              name: this.$t('common.empty'),
              id: null,
            })
          }
          this.form.AddresseeEmailArray.push(addresseeTemp)
          this.addresseeTemp = ''
        }
      )
    },
    handleTemplateChange(val) {
      this.form.EmailContent = val
    },
    handleSelectTemplate() {
      this.showSelectTemplateVisible = true
    },
    handleEmailRemove(val) {
      this.form.Addressee.splice(
        this.form.Addressee.findIndex((i) => i === val),
        1
      )
      this.form.AddresseeEmailArray.splice(
        this.form.AddresseeEmailArray.findIndex((i) => i === val.email),
        1
      )
    },
    handleImportEmails() {
      // console.log('开始批量验证')importEmailTemp
      this.importEmailTemp = this.importEmailTemp.trim()
      console.log(this.importEmailTemp, this.importEmailTemp.length)
      if (this.importEmailTemp.length !== 0) {
        let importEmailTempArray = this.importEmailTemp
          .split('\n')
          .map((m) => m.trim())
          .filter((m) => m)
          .filter(this.checkEmailAddress)
        if (importEmailTempArray.length > 0) {
          importEmailTempArray = this.$common
            .uniqueArray(importEmailTempArray)
            .filter((m) => !this.form.Addressee.some((e) => e.email === m))
          this.form.Addressee.push(
            ...importEmailTempArray.map((m) => ({
              email: m,
              name: this.$t('common.empty'),
              id: null,
            }))
          )
          // this.form.Addressee.push(...importEmailTempArray.map(m => this.handleGetIdByEmailRet(m)))
          // TODO: 用这个可以实现获取用户昵称 importEmailTempArray.map(m => this.handleGetIdByEmail(m))
          console.log(importEmailTempArray)
          for (const i in importEmailTempArray) {
            const m = importEmailTempArray[i]
            console.log(m)
            if (this.form.AddresseeEmailArray.indexOf(m) === -1) {
              this.form.AddresseeEmailArray.push(m)
            }
          }

          this.importEmailTemp = ''
        } else {
          this.$message({
            message: this.$t('email.pleaseInputValidEmail'),
            type: 'warning',
          })
          return false
        }
      } else {
        this.$message({
          message: this.$t('email.cannotBeEmpty'),
          type: 'warning',
        })
        return false
      }
    },
    checkEmailAddress(szMail) {
      const szReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
      const bChk = szReg.test(szMail)
      console.log(bChk, '111')
      return bChk
    },
    handleUploadEmails() {
      console.log('处理上传邮箱')
    },
    getUploadEmail() {
      console.log('获取上传信息')
    },
    handleShowUploadEmails() {
      if (this.showUploadEmailsVisible) {
        this.showUploadEmailsVisible = false
      } else {
        this.showUploadEmailsVisible = true
      }
    },
    getRandomNum(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min)
    },
    changeFile(file, fileList) {
      if (file.status === 'ready') {
        // 已上传文件列表如果存在 2 条记录，移除第一条，实现替换效果
        if (fileList.length === 2) {
          fileList.shift()
        }

        // 手动开始上传
        this.$refs.uploadEmail.submit()
      }
    },
    uploadHandler(params) {
      // const isLt2M = params.file.size <= 2
      const isLt2M = params.file.size / 1024 / 1024 <= 2
      if (!isLt2M) {
        this.$message({
          message: this.$t('email.uploadFileCannotGreaterThan2M'),
          type: 'warning',
        })
        return false
      }

      // 调用 element ui 进度条
      params.onProgress({ percent: this.getRandomNum(19, 99) })
      setTimeout(() => {
        this.readText(params)
      }, 100)
    },
    async readText(params) {
      // UTF-8,GBK,GB2312
      const readFile = new FileReader()
      readFile.onload = (e) => {
        this.importEmailTemp = e.target.result
        console.log(e.target.result)
        params.onProgress({ percent: 100 }) // 调用 element ui 进度条
        params.onSuccess() // 调用 element ui 上传成功方法
      }
      readFile.readAsText(params.file)
    },
    querySearchAsync(queryString, cb) {
      getAction(
        { name: queryString.trim() },
        'emailMarketing/searchSenderNames'
      )
        .then((res) => {
          if (res.code === 20000) {
            cb(res.data)
          } else {
            cb()
          }
        })
        .catch((e) => {
          cb()
        })
    },
  },
}
</script>

<style scoped>
.footer-operate {
  text-align: center;
}
/* 去掉已上传文件列表的文件移除动画 */
/deep/ .el-list-leave-active {
  transition: none;
}
/deep/ .el-list-leave-active {
  opacity: 0;
}
/deep/ .el-upload-list {
  max-height: 26px;
}
.receiving {
}
</style>
